//
//  UIView+Dev.swift
//  CodingTest
//
//  Created by LYPC on 2021/11/19.
//

import UIKit

public extension UIView {

    /// 给layer添加阴影
    ///
    /// - Parameter color:  颜色
    /// - Parameter blur:   blur radius
    /// - Parameter opacity: 不透明
    /// - Parameter rect:   shadowPath
    ///
    func addShadow(withRect rect: CGRect, color: UIColor, blur: CGFloat, opacity: CGFloat, cornerRadius: CGFloat = 0) {
        let bLayer = layer
        guard
            let superV = superview,
            bLayer.masksToBounds else {
                bLayer.addShadow(withRect: rect, cornerRadius: cornerRadius, color: color, blur: blur, opacity: opacity)
                return
        }
        /// 创建一个背景view
        let bg = UIView()
        bg.isUserInteractionEnabled = false
        bg.backgroundColor = .clear
        superV.insertSubview(bg, belowSubview: self)
        bg.layer.addShadow(withRect: rect, cornerRadius: cornerRadius, color: color, blur: blur, opacity: opacity)
        bg.snp.makeConstraints { (m) in
            m.edges.equalTo(self)
        }
    }

    /// 设置圆角 半径
    func setCornerRadius(_ radius:CGFloat) {
        let bLayer = layer
        bLayer.cornerRadius = radius
        bLayer.masksToBounds = true
    }
}

extension CALayer {
    /// 给layer添加阴影
    ///
    /// - Parameter color:  颜色
    /// - Parameter blur:   blur radius
    /// - Parameter opacity: 不透明
    /// - Parameter rect:   shadowPath
    ///
    func addShadow(withRect rect: CGRect, cornerRadius: CGFloat, color: UIColor, blur: CGFloat, opacity: CGFloat) {
        self.shadowColor = color.cgColor
        self.shadowRadius = blur
        self.shadowOpacity = Float(opacity)
        self.shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).cgPath
    }
}
